let app = getApp();
Page({

  data: {
    id: 0,               
    url: '',              
    consultant: {},     
    pageNum: 1,        
    pageSize: 3,        
    message: [],          
    hasMore: true,      
    consultantId: null,
  
    chargingList: [],    
    courses: [], 
    evaluationList: [],



    // 问答加载状态
    replyLoading: true, 
    replyError: ''      
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('接收的咨询师编号：', options.id);
    if (!options.id || isNaN(options.id)) {
      wx.showToast({
        title: '参数错误，无法加载详情',
        icon: 'none',
        duration: 2000
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 2000);
      return;
    }

    // 初始化基础参数
    this.setData({
      id: parseInt(options.id),
      url: app.globalData.url 
    });

    // 加载各类数据
    this.getConsultantBaseInfo();   
    this.getChargingStandards();    
    this.getMessage();             
    this.getEvaluationList();
    this.fetchData(); 
  },
  goToConsult() {
    const consultantId = this.data.id;
    if (!consultantId) {
      wx.showToast({
        title: '参数错误，无法跳转',
        icon: 'none'
      });
      return;
    }
    
    // 跳转至指定页面，并携带consultantId参数
    wx.navigateTo({
      // 页面路径需以绝对路径开头（/），参数用?拼接
      url: '/pages/consult/consultDetails/zixun/zixun?consultantId=' + consultantId,
      fail: (err) => {
        console.error('跳转咨询页面失败：', err);
        wx.showToast({
          title: '无法打开咨询页面',
          icon: 'none'
        });
      }
    });
    

  },
  goToReview() {
    const consultantId = this.data.id;
    if (!consultantId) {
      wx.showToast({
        title: '参数错误，无法跳转',
        icon: 'none'
      });
      return;
    }
    wx.navigateTo({
      url: '/pages/consult/consultDetails/review/review?consultantId=' + consultantId,
      fail: (err) => {
        console.error('跳转评价页面失败：', err);
        wx.showToast({
          title: '无法打开评价页面',
          icon: 'none'
        });
      }
    });
  },
  fetchData() {
   
    const consultantId = this.data.id;
    wx.request({
     
    url: this.data.url + 'consultant/' + consultantId + '/course',
      method: 'GET', 
      success: (res) => {
        console.log('课程接口返回:', res.data);
        if (res.data && res.data.code === 200) {
         
          
          this.setData({
            courses: res.data.data || [] 
          });
        } else {
          wx.showToast({
            title: res.data?.msg || '课程数据加载失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('课程请求失败：', err);
        wx.showToast({
          title: '网络错误，无法加载课程',
          icon: 'none'
        });
      }
    });
  },
  // 点击“查看更多课程”
  goMoreCourses() {
    const consultantId = this.data.id;
    if (!consultantId) {
      wx.showToast({
        title: '参数错误，无法查看课程',
        icon: 'none'
      });
      return;
    }
    wx.navigateTo({
      url: '/pages/consult/consultDetails/courseList/courseList?consultantId=' + consultantId
    });
  },

  getEvaluationList() {
    const {consultantId}  = this.data;
    wx.request({
      url: this.data.url + 'consultantEvaluation/consultant/' + this.data.id, 
      method: 'GET',
      success: (res) => {
        console.log(res);
        if (res.data && res.data.code === 200) {
          const formatList = res.data.data.map(item => ({
            ...item,
            evaluationTimeFormat: this.formatTime(item.evaluationTime)
          }));
          this.setData({ evaluationList: formatList });
        } else {
          wx.showToast({
            title: '评价数据加载失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 时间格式化工具（将日期转为相对时间）
   * @param {string} dateStr - 接口返回的时间字符串（如：2025-08-15）
   * @return {string} 格式化后的时间（如：“昨天”“3天前”）
   */
  formatTime(dateStr) {
    const today = new Date();
    const evaluationDate = new Date(dateStr);
    const diffDays = Math.floor((today - evaluationDate) / (1000 * 60 * 60 * 24));
    
    if (diffDays === 0) return '今天';
    if (diffDays === 1) return '昨天';
    if (diffDays < 7) return diffDays + '天前';
    // 超过一周则显示原日期
    return evaluationDate.getFullYear() + '-' + 
    (evaluationDate.getMonth() + 1).toString().padStart(2, '0') + '-' + 
    evaluationDate.getDate().toString().padStart(2, '0');
  },

  /**
   * 查看更多评价（跳转到评价列表页，携带consultantId）
   */
  goMoreEvaluation() {
    const consultantId = this.data.id; 
    wx.navigateTo({
      url: '/pages/consult/consultDetails/evaluation/evaluation?consultantId=' + consultantId
    });
  },

 
  getMessage() {
    wx.request({
      data: {
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize,
      },
      url: this.data.url + 'question/qa/' + this.data.id,
      success: (resp) => {
        if (resp.data && resp.data.code === 200) {
          const dataList = resp.data.data?.list || [];
          this.setData({
            message: dataList,
            replyLoading: false,
            replyError: ''
          });
        }
      },
      fail: (err) => {
        console.error('问答请求失败：', err);
      }
    });
  },
  goToAllAnswers() {
    const consultantId = this.data.id;
    if (consultantId) {
      wx.navigateTo({
        url: '/pages/consult/consultDetails/answer/answer?consultantId=' + consultantId,
        fail: (err) => {
          console.error('跳转至全部回复失败：', err);
          wx.showToast({
            title: '无法查看更多回复',
            icon: 'none'
          });
        }
      });
    } else {
      wx.showToast({
        title: '参数错误，无法加载',
        icon: 'none'
      });
    }
  },

  /**
   * 获取咨询师基本信息
   */
  getConsultantBaseInfo() {
    wx.request({
      url: this.data.url + 'consultant/' + this.data.id,
      success: (resp) => {
        if (resp.data && resp.data.code === 200 && resp.data.data) {
          this.setData({
            consultant: resp.data.data
          });
        } else {
          wx.showToast({
            title: resp.data?.msg || '获取咨询师信息失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取咨询师信息失败：', err);
        wx.showToast({
          title: '网络错误，无法加载咨询师信息',
          icon: 'none'
        });
      }
    });
  },

  getChargingStandards() {
    this.setData({
      chargingLoading: true,
      chargingError: ''
    });

    wx.request({
      url: this.data.url + 'chargingStandards/consultant/' + this.data.id,
      method: 'GET',
      data: {
        limit: 3 
      },
      success: (res) => {
        this.setData({ chargingLoading: false });

        if (res.data && res.data.code === 200) {
          const limitedList = res.data.data?.slice(0, 3) || [];
          this.setData({
            chargingList: limitedList
          });
          
          if (this.data.chargingList.length === 0) {
            this.setData({
              chargingError: '暂无收费标准数据'
            });
          }
        } else {
          this.setData({
            chargingError: res.data?.msg || '获取收费标准失败'
          });
        }
      },
      fail: (err) => {
        console.error('加载收费标准失败：', err);
        this.setData({
          chargingLoading: false,
          chargingError: '网络请求失败，请稍后重试'
        });
      }
    });
  },

  /**
   * 查看证书详情
   */
  viewCertificate() {
    if (this.data.consultant.id) {
      wx.navigateTo({
        url: '/pages/consult/consultDetails/certificate/certificate?consultantId=' + this.data.consultant.id
      });
    } else {
      wx.showToast({
        title: '暂无证书信息',
        icon: 'none'
      });
    }
  },

  /**
   * 查看更多收费标准
   */
  goMoreCharging() {
    wx.navigateTo({
      url: '/pages/consult/consultDetails/chargingStandards/chargingStandards?consultantId=' + this.data.id
    });
  },

 
  /**
   * 页面下拉刷新
   */
  onPullDownRefresh() {
    this.setData({
      pageNum: 1,
      hasMore: true,
      replyLoading: true
    }, () => {
      this.getConsultantBaseInfo();
      this.getChargingStandards();
      this.getMessage(); 
      this.getEvaluationList()
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底（加载更多）
   */
  onReachBottom() {
    if (this.data.replyLoading || !this.data.hasMore) return;
    this.setData({
      pageNum: this.data.pageNum + 1,
      replyLoading: true
    }, () => {
      this.getMessage(true);
    });
  },

  /**
   * 分享功能
   */
  onShareAppMessage() {
    return {
      title: (this.data.consultant.name || '咨询师') + '的咨询详情',
      path: '/pages/consult/consultDetails/consultDetails?id=' + this.data.id
    };
  }
});